package dubboRpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable{

    private ChannelHandlerContext context;//上下文
    private String result;//返回的结果
    private String para;//客户端调用方法时，传入的参数

    //与服务器的连接创建后，就会被调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context=ctx;//其他方法需要调用
//        super.channelActive(ctx);
    }
    //设置参数
    public void setPara(String para) {
        this.para = para;
    }

    /**
     * 被代理对象，发送给服务器后 wait 等待被唤醒(channlRead) 返回结果
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("call 被调用");
        context.writeAndFlush(para);
        //进行wait,等待channelRead得到服务器返回的结果后进行唤醒
        wait();
        return result;
    }
    //收到数据后会被调用
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        result=msg.toString();
        //唤醒等待的线程
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        super.exceptionCaught(ctx, cause);
        System.out.println("出现异常");
        ctx.close();
    }
}
